package net.cattaka.allcom.android.net;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.LinkedList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.ByteArrayBuffer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import net.cattaka.allcom.android.entity.Card;

public class ServerInterface {
    public static final boolean DEBUG_FLG = true;
    public static final String TAG = "ServerInterface";

    public static final String API_URL = "http://www.cattaka.net/felicathon/RegistCoupleJson.php";

    private static final String JSON_TEST ="{\"member\":[{\"id\":\"90001\",\"name\":\"\u4f4f\u53cb\u5b5d\u90ce\",\"known\":\"0\"}," +
    		"{\"id\":\"90002\",\"name\":\"ASO\",\"known\":\"0\"},{\"id\":\"90003\",\"name\":\"ARITAMA\",\"known\":\"0\"}," +
    		"{\"id\":\"90004\",\"name\":\"\u304b\u3063\u3061\",\"known\":\"0\"}," +
			"{\"id\":\"91001\",\"name\":\"\u306b\u3083\u3093\u3053\u5148\u751f\",\"known\":\"0\"}," +
			"{\"id\":\"91002\",\"name\":\"\u30c6\u30b9\u30c8\",\"known\":\"0\"}," +
    		"{\"id\":\"91003\",\"name\":\"Cattaka\",\"known\":\"0\"}]}";
    /**
     * 出席者リストを取得する.
     * 
     * @param me 自分のID
     * @param target idに値が渡された場合は登録を行う。nullの場合は参照のみ
     * @return
     * @throws IOException 
     * @throws HttpResponseException 
     */
    public static List<Card> getCardList(String me, String target) throws HttpResponseException, IOException {
        LinkedList<Card> result = new LinkedList<Card>();
        
        HttpUriRequest urlRequest = new HttpGet(generateApiUrl(me, target));
        String response = httpConnect(urlRequest);

        if(DEBUG_FLG) Log.d(TAG, response);

        try {
            JSONObject jsonObj = new JSONObject(response);
            JSONArray jsonArray = jsonObj.getJSONArray("member");
            
            int len = jsonArray.length();
            for (int i = 0; i <  len; i++) {
                JSONObject obj = jsonArray.getJSONObject(i);
                Card tmp = new Card();
                tmp.setId(obj.getInt("id"));
                tmp.setName(obj.getString("name"));
                tmp.setKnown(obj.getInt("known"));
                result.add(tmp);
            }
        } catch (JSONException e) {
            Log.e(TAG, "JSONException", e);
        }
        
         return result;
    }
    
    /**
     * HttpConnect
     * 
     * @param url
     * @throws IOException
     * @throws HttpResponseException
     * @return
     */
    private static String httpConnect(HttpUriRequest urlRequest) throws IOException,
            HttpResponseException {

        InputStream in = null;

        DefaultHttpClient con = new DefaultHttpClient();
        HttpResponse res = con.execute(urlRequest);

        if (res.getStatusLine().getStatusCode() == 200) {

            HttpEntity entity = res.getEntity();
            in = entity.getContent();

        } else {
            throw new HttpResponseException(res.getStatusLine().getStatusCode(), res
                    .getStatusLine().getReasonPhrase());
        }

        byte[] buff = new byte[512];
        ByteArrayBuffer bab = new ByteArrayBuffer(512);

        int len = 0;
        while( (len = in.read(buff)) != -1 ) {
            bab.append(buff, 0, len);
        }

        String result = null;
        try {
            result = new String(bab.buffer(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
        }

        return result;

    }
    
    private static List<Card> generateCardList(String json) {
        List<Card> list = null;
        
        return list;
    }

    /**
     * APIにGETアクセスするURLを生成する.
     * 
     * @param id
     * @return
     */
    private static String generateApiUrl(String me, String target) {
        if(me != null && target != null) {
            return String.format(API_URL + "?id=%s&target=%s", me, target);
        } else if(me != null) {
            return String.format(API_URL + "?id=%s", me);
        } else {
            throw new IllegalArgumentException("id must be set.");
        }
    }


}
